import { useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min'
import styles from './index.module.scss'
const NotFound = () => {
  const history = useHistory()
  const [count, setCount] = useState(5)
  // 创建定时器
  const timerRef = useRef(-1)

  useEffect(() => {
    timerRef.current = setInterval(() => {
      // 为了能够在页面中展示计时效果 需要修改状态
      setCount((prevCount) => prevCount - 1)
    }, 1000)

    // 因为依赖项为空数组，所以返回的函数在组件卸载时执行
    return () => {
      clearInterval(timerRef.current)
    }
  }, [])

  useEffect(() => {
    if (count === 0) {
      history.replace('/home')
    }
  }, [count, history])

  return (
    <div className={styles.root}>
      <h1>对不起，您访问的页面不存在~</h1>
      <p>
        将在 {count} 秒后，返回首页(或者：点击立即返回
        <Link to="/home">首页</Link>)
      </p>
    </div>
  )
}

export default NotFound
